//
//  StringManager.m
//  MapEdit
//
//  Created by Steven Canfield on 7/13/07.
//  Copyright 2007 __MyCompanyName__. All rights reserved.
//

#import "StringManager.h"


@implementation StringManager
- (id)initWithData:(NSData *)data {
	self = [super init];
	if( self ) {
		stringArray = [[NSMutableArray alloc] init];
		
		chk_str_t str;
		
		int dataIndex = 0;
		[data getBytes:&str range:NSMakeRange( dataIndex, sizeof( chk_str_t ))];
		swap_chk_str( &str );
		int strIndex;
		for( strIndex = 0; strIndex < str.count; strIndex++ ) {
			[stringArray addObject:[NSString string]];
			stringUsed[ strIndex ] = NO;
		}
		
		
		char * dataBytes = (char *)[data bytes];
		
		for( strIndex = 0; strIndex < str.count; strIndex++ ) {
			int offset = str.offset[ strIndex ];
			NSString * buffer = [NSString stringWithCString:&dataBytes[ offset ] encoding:NSASCIIStringEncoding];
			[stringArray replaceObjectAtIndex:strIndex withObject:buffer];
			if( [buffer isEqualToString:@""] ) {
				stringUsed[ strIndex ] = YES;
			}
		}
	}
	return self;
}

- (NSString *)stringAtIndex:(int)index {
	if( index == 0 ) {
		return @"";
	}
	NSString * string = [stringArray objectAtIndex:index-1];
	return string;
}

- (int)newStringIndex {
	int strIndex = 0;
	for( strIndex = 0; strIndex < [stringArray count]; strIndex++ ) {
		if( stringUsed[ strIndex ] == NO ) {
			stringUsed[ strIndex ] = YES;
			return strIndex;
		}
	}
	return -1;
}

- (void)setStringAtIndex:(int)index toString:(NSString *)string {
	[stringArray replaceObjectAtIndex:index withObject:string];
}

- (NSData *)serializeStrings {
	return [NSData data];
}


@end
